import {
  Router
} from 'express'
import _ from 'lodash'
const router = Router()
import Iredis from '../plugs/Iredis'
import axios from 'axios'
import mysql from '../plugs/mysql'
import md5 from 'MD5'
//微信登录
router.get('/login', async (req, res, next) => {
  try {
    const wxState = new Date().getTime()
    let config = req.app.get('$config');
    let scope = req.query.scope || `snsapi_base`
    let returnUrl = req.query.returnUrl || '/'
    res.cookie('wxState', wxState, {
      maxAge: config.get('sessMaxAge'),
      page: '/'
    })
    const url = `${config.get('appDomain')}/oauth/wx/callback?scope=${scope}&returnUrl=${returnUrl}`
    const redirectUri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.get('appID')}&redirect_uri=${encodeURIComponent(url)}&response_type=code&scope=${scope}&state=${wxState}#wechat_redirect`
    return res.redirect(redirectUri)
  } catch (error) {
    console.log(error);
    res.send(error)
  }
})
router.get('/wx/callback', async (req, res, next) => {
  try {
    let config = req.app.get('$config');
    const {
      code,
      state,
      scope,
      returnUrl
    } = req.query;
    if (state == req.cookies['wxState']) {
      res.clearCookie('wxState');
      const data = await getWxAccessToken(config.get('appID'), config.get('appSecret'), code)
      let {
        access_token,
        openid
      } = data;
      const userinfo = await getWxUserInfo(access_token, openid);
      let myConnect = await mysql.getConnect();
      let selectSql = `SELECT id,open_id,nickname,sex,city,province,headimgurl,country FROM wx_user where open_id = ${myConnect.escape(userinfo.openid)}`
      let users = await mysql.query(myConnect, selectSql);
      let Sql = `${users.length?'update':'insert into'} wx_user set ?`
      let params = {
        'open_id': openid,
        'nickname': userinfo.nickname,
        'sex': userinfo.sex,
        'language': userinfo.language,
        'city': userinfo.city,
        'province': userinfo.province,
        'headimgurl': userinfo.headimgurl,
        'country': userinfo.country
      }
      let resuleData = await mysql.query(myConnect, Sql,params);
      let userid = resuleData.insertId || users[0].id
      // 生成session
      let sessionSql = `insert into session set ?`
      userinfo.open_id = userinfo.openid
      userinfo.id = userid
      let session_key = md5(parseInt(new Date().getTime()/1000,0)+''+Math.random().toString(36).substr(2,15))
      let sessionParams = {
        session_key,
        data:JSON.stringify(userinfo)
      }
      let sessionResult = await mysql.query(myConnect,sessionSql,sessionParams);
      await mysql.release(myConnect);
      if(sessionResult.insertId>0){
        res.cookie(config.get('sessIdKey'), session_key, {
          maxAge: config.get('sessMaxAge'),
          page: '/'
        })
        return res.redirect(returnUrl)
      }
      return res.send('请刷新页面')
    } else {
      return res.send(req.query)
    }

  } catch (error) {
    return res.send('数据错误')
  }
})
async function getWxAccessToken(appid, secret, code) {
  try {
    const accessTokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
    const result = await axios.get(accessTokenUrl)
    return result.data
  } catch (error) {
    console.log(error)
    return null
  }
}
async function getWxUserInfo(token, openid) {
  try {
    const userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openid}&lang=zh_CN`
    const result = await axios.get(userInfoUrl)
    return result.data
  } catch (error) {
    console.log(error)
    return null
  }
}
export default router